<script setup lang="ts">
import { h, ref, reactive, onMounted } from 'vue'
import { NCard, NForm, NGrid, NFormItemGi, NIcon, NSpace, NDivider, NInput, NInputNumber, NSelect, NButton, NTreeSelect, NPopover, NTree, NPopconfirm, useNotification, useDialog } from 'naive-ui'
import type { FormInst, FormRules, TreeOption } from 'naive-ui'

import { useUserStore } from '@/stores/userStore'
import { useDictStore } from '@/stores/dictStore'
import { useOrgStore } from '@/stores/orgStore'

import http from '@/tools/http'
import { toTree } from '@/tools/tree'
import type { Tree } from '@/tools/tree'

import { PlusOutlined, DeleteOutlined } from '@vicons/antd'

import orgUserManage from './org-user-manage.vue'


const notification = useNotification()
const dialog = useDialog()
const dictStore = useDictStore()
const userStore = useUserStore()
const orgStore = useOrgStore()

type OrgData = {
    orgCode?: string
    orgName?: string
    orgStatus?: string
    orgType?: string
    orgSort?: number
    orgParent?: string
    remark?: string
}

type UserInfo = {
    userId: string
    userName: string
}

const title = ref<string>("")
const currentOrg = ref<OrgData>({})
const orgSearch = ref("")
let orgTreeData = ref<any>([])
const selectedKeys = ref<string[]>([])
const orgUserList = reactive<UserInfo[]>([])
const formRef = ref<FormInst | null>(null)
const formData = reactive<OrgData>({
    orgCode: "",
    orgName: "",
    orgStatus: "0",
    orgType: "0",
    orgSort: 999,
    orgParent: "",
    remark: ""
})

const formRules: FormRules = ({
    orgCode: {
        required: true,
        message: '请输入机构编码',
        trigger: ['input']
    },
    orgName: {
        required: true,
        message: '请输入机构名称',
        trigger: ['input']
    },
    orgStatus: {
        required: true,
        message: '请输入机构状态',
        trigger: ['input']
    },
    orgType: {
        required: true,
        message: '请输入机构类型',
        trigger: ['input']
    }
})

onMounted(() => {
    listOrgInfo(null)
})


function treeNodeClicked(info: { option: Tree | TreeOption }) {
    return {
        onClick: () => {
            openOrg(info.option.data)
        }
    }
}

function renderSuffix(info: { option: Tree | TreeOption, checked: boolean, selected: boolean }) {
    return h(
        NSpace, null,
        () => [
            userStore.hasAuth("org:add") ? h(
                NPopover,
                {
                    style: "width: 150px",
                    headerStyle: { padding: 0 },
                    contentStyle: { padding: 0 },
                    placement: "bottom"
                },
                {
                    trigger: () => h(
                        NIcon,
                        {
                            size: 15,
                            style: "line-height: 2em;"

                        },
                        { default: () => h(PlusOutlined) }
                    )
                    ,
                    header: () => h(
                        NButton,
                        {
                            style: "width:100%",
                            quaternary: true,
                            onclick: () => openAddOrgInfo(info.option.data, true)
                        },
                        () => "添加同级机构"
                    ),
                    default: () => h(
                        NButton,
                        {
                            style: "width:100%",
                            quaternary: true,
                            onclick: () => openAddOrgInfo(info.option.data, false)
                        },
                        () => "添加子级机构"
                    )
                }
            ) : null,
            userStore.hasAuth("org:delete") ? h(
                NPopconfirm,
                {
                    onPositiveClick: (e: MouseEvent) => deleteOrgInfo()
                },
                {
                    trigger: () => {
                        return h(
                            NIcon,
                            {
                                size: 15,
                                style: "line-height: 2em;",
                                onclick: () => openDeleteOrgInfo(info.option.data)
                            },
                            { default: () => h(DeleteOutlined) }
                        )
                    },
                    default: () => { return "确认删除该机构及下级机构么？" }
                }
            ) : null
        ]
    )
}

function openOrg(org: OrgData) {
    title.value = `机构【${org.orgName}】信息`
    selectedKeys.value.length = 0
    if (org.orgCode) {
        selectedKeys.value.push(org.orgCode)
    }
    currentOrg.value = org
    formData.orgCode = org.orgCode
    formData.orgName = org.orgName
    formData.orgStatus = org.orgStatus
    formData.orgType = org.orgType
    formData.orgSort = org.orgSort
    formData.orgParent = org.orgParent
    formData.remark = org.remark
    getOrgUserList()
}

function openAddOrgInfo(org: OrgData, sameParent: boolean) {
    title.value = "新增机构"
    formData.orgCode = ""
    formData.orgName = ""
    formData.orgStatus = "0"
    formData.orgType = "0"
    formData.orgSort = 999
    formData.orgParent = ""
    if (org === null) {
        formData.orgParent = ""
    } else {
        if (sameParent) {
            formData.orgParent = org.orgParent
        } else {
            formData.orgParent = org.orgCode
        }
    }
    formData.remark = ""
    orgUserList.length = 0
}

function openEditOrgInfo(row: OrgData) {
    title.value = `机构【${row.orgName}】信息 - 编辑`
    formData.orgCode = row.orgCode
    formData.orgName = row.orgName
    formData.orgStatus = row.orgStatus
    formData.orgType = row.orgType
    formData.orgSort = row.orgSort
    formData.orgParent = row.orgParent
    formData.remark = row.remark
}

function openDeleteOrgInfo(row: OrgData) {
    formData.orgCode = row.orgCode
    formData.orgName = row.orgName
    formData.orgStatus = row.orgStatus
    formData.orgType = row.orgType
    formData.orgSort = row.orgSort
    formData.orgParent = row.orgParent
    formData.remark = row.remark
}

function submit() {
    formRef.value?.validate((errors) => {
        if (!errors) {
            dialog.create({
                title: '温馨提示',
                content: '确定提交吗？',
                positiveText: '确定',
                negativeText: '取消',
                onPositiveClick: () => {
                    if (title.value.includes('编辑')) {
                        updateOrgInfo()
                    }
                    if (title.value.includes('新增')) {
                        addOrgInfo()
                    }
                }
            })
        }
    })
}

function listOrgInfo(org: OrgData | null) {
    http.post("/org/list").then(({ data }) => {
        if (data.code === "0") {
            orgStore.loadOrgInfo(data.data)
            orgTreeData.value = toTree(data.data, "orgParent", null, "orgCode", "orgName", "orgCode")
            if (org === null) {
                openOrg(orgTreeData.value[0].data)
            } else {
                openOrg(org)
            }
        }
    })
}

function addOrgInfo() {
    http.post("/org/add", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '添加成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            listOrgInfo(formData)
        }
    })
}

function updateOrgInfo() {
    http.post("/org/update", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '修改成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            listOrgInfo(formData)
        }
    })
}

function deleteOrgInfo() {
    http.post("/org/delete", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '删除成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            listOrgInfo(formData)
        }
    })
}

function getOrgUserList() {
    const request = {
        orgCode: formData.orgCode
    }
    http.post("/org/user/list", request).then(({ data }) => {
        if (data.code === "0") {
            orgUserList.length = 0
            for (let i = 0; i < data.data.length; i++) {
                orgUserList.push(data.data[i])
            }
        }
    })
}

function removeUser(userId: string) {
    const request = {
        orgCode: formData.orgCode,
        userId: userId
    }
    http.post("/org/user/remove", request).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '移除成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            getOrgUserList()
        }
    })
}
</script>

<template>
    <div class="flame-container">
        <n-card :content-style="{ display: 'flex', padding: '0px' }" :bordered="false">
            <div class="content-left">
                <div class="content-left-top">
                    <n-input v-model:value="orgSearch" type="text" placeholder="输入机构名称关键字过滤" clearable />
                </div>
                <div class="content-left-content">
                    <n-tree block-line :data="orgTreeData" :pattern="orgSearch" :show-irrelevant-nodes="false"
                        :node-props="treeNodeClicked" :render-suffix="renderSuffix" :selected-keys="selectedKeys" />
                </div>
            </div>
            <div class="content-right">
                <div class="content-right-title">
                    {{ title }}
                </div>
                <div class="content-right-body">
                    <n-form class="content-right-form" ref="formRef" :model="formData" :rules="formRules"
                        :disabled="!title.includes('编辑') && !title.includes('新增')" label-placement="left"
                        label-width="78px" label-align="left" require-mark-placement="left">
                        <n-grid :cols="2" :x-gap="10" :y-gap="0">
                            <n-form-item-gi :span="1" label="机构编码" path="orgCode">
                                <n-input :disabled="!title.includes('新增')" v-model:value="formData.orgCode"
                                    placeholder="请输入机构编码" />
                            </n-form-item-gi>
                            <n-form-item-gi :span="1" label="机构名称" path="orgName">
                                <n-input v-model:value="formData.orgName" placeholder="请输入机构名称" />
                            </n-form-item-gi>
                            <n-form-item-gi :span="1" label="机构类型" path="orgType">
                                <n-select v-model:value="formData.orgType" :options="dictStore.dict('ORG_TYPE')"
                                    placeholder="请选择机构类型" />
                            </n-form-item-gi>
                            <n-form-item-gi :span="1" label="机构状态" path="orgStatus">
                                <n-select v-model:value="formData.orgStatus" :options="dictStore.dict('ORG_STATUS')"
                                    placeholder="请选择机构状态" />
                            </n-form-item-gi>
                            <n-form-item-gi :span="1" label="上级机构" path="orgParent">
                                <n-tree-select v-model:value="formData.orgParent" :options="orgTreeData"
                                    default-value="" placeholder="请选择上级机构" clearable />
                            </n-form-item-gi>
                            <n-form-item-gi :span="1" label="机构排序" path="orgSort">
                                <n-input-number v-model:value="formData.orgSort" :min="1" :max="999"
                                    placeholder="请输入机构排序" style="width:100%" />
                            </n-form-item-gi>
                            <n-form-item-gi :span="2" label="备注" path="remark">
                                <n-input v-model:value="formData.remark" placeholder="请输入备注" clearable />
                            </n-form-item-gi>
                        </n-grid>
                    </n-form>
                    <n-divider style="margin-top:0;margin-bottom:12px;" title-placement="left">机构成员列表</n-divider>
                    <div style="padding: 0 20px;">
                        <org-user-manage :disabled="!title.includes('编辑') && !title.includes('新增')"
                            :org-user-list="orgUserList" :remove-user="removeUser" />
                    </div>
                </div>
                <div class="content-right-bottom" v-if="userStore.hasAuth('org:edit')">
                    <n-space>
                        <n-button v-if="!title.includes('编辑') && !title.includes('新增')"
                            @click="openEditOrgInfo(currentOrg)">
                            编辑
                        </n-button>
                        <n-button v-if="title.includes('编辑') || title.includes('新增')" @click="openOrg(currentOrg)">
                            取消
                        </n-button>
                        <n-button v-if="title.includes('编辑') || title.includes('新增')" @click="submit()">
                            提交
                        </n-button>
                    </n-space>
                </div>
            </div>
        </n-card>
    </div>
</template>

<style scoped>
.content-left {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    width: 330px;
    border-right: 1px solid var(--n-border-color);
}

.content-left .content-left-top {
    display: flex;
    gap: 3px;
    padding: 5px;
    height: 34px;
}

.content-left .content-left-content {
    height: 100%;
}

.content-right {
    position: absolute;
    top: 0;
    left: 330px;
    right: 0;
    bottom: 0;
    display: flex;
    flex: 1;
    flex-direction: column;
}

.content-right .content-right-body {
    position: absolute;
    top: 48px;
    right: 0;
    bottom: 63px;
    width: 100%;
    overflow-y: auto;
}

.content-right .content-right-title {
    height: 48px;
    line-height: 48px;
    margin-left: 20px;
    margin-right: 20px;
    font-weight: 700;
    font-size: 16px;
    border-bottom: .8px solid var(--n-border-color);
}

.content-right .content-right-form {
    padding: 16px 20px 0px;
}

.content-right .content-right-auth {
    padding: 0 20px;
}

.content-right .content-right-bottom {
    position: absolute;
    bottom: 0;
    left: 1px;
    right: 0;
    padding: 14px 20px 14px;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid var(--n-border-color);
    background-color: var(--n-color);
}

.menu-icon-suffix-button {
    display: flex;
}

.menu-icon-suffix-button:hover {
    cursor: pointer;
}

.icon-table {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
}

.icon-table .icon-unit {
    width: 38px;
    height: 38px;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid var(--flame-menu-config-icon-border-color);
}

.icon-table .icon-unit:hover {
    cursor: pointer;
}
</style>